<template>
	<div class="infinite-scroll-list" ref="scrollContainer" @scroll="handleScroll">
		<el-space wrap :size="20">
			<div v-for="(item, index) in items" :key="index">
				<!-- 传递新的字段到 PhotoCard 组件 -->
				<PhotoCard :author_id="item.author_id" :photo_id="item.photo_id" :public="item.public" :url="item.url"
					:thumbnail_url="item.thumbnail_url" :author="item.author" :name="item.name"
					:description="item.description" />
			</div>
		</el-space>
		<div v-if="loading" class="loading-indicator">
			<el-skeleton style="width: 240px" animated>
				<template #template>
					<el-skeleton-item variant="image" style="width: 240px; height: 240px" />
					<div style="padding: 14px">
						<el-skeleton-item variant="h3" style="width: 50%" />
						<div style="
              display: flex;
              align-items: center;
              justify-content: space-between;
              margin-top: 16px;
              height: 16px;
            ">
							<el-skeleton-item variant="text" style="margin-right: 16px" />
							<el-skeleton-item variant="text" style="width: 30%" />
						</div>
					</div>
				</template>
			</el-skeleton>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import PhotoCard from './PhotoCard.vue'

	const items = ref([])
	const loading = ref(false)
	const page = ref(1)
	const scrollContainer = ref(null)

	const fetchData = async () => {
		loading.value = true
		// 模拟异步加载数据
		const newItems = await new Promise((resolve) => {
			setTimeout(() => {
				const data = Array.from({
					length: 10
				}, (_, i) => ({
					author_id: `author_${items.value.length + i + 1}`,
					photo_id: `photo_${items.value.length + i + 1}`,
					public: Math.random() > 0.5 ? 1 : 0, // 随机生成 0 或 1
					url: 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png',
					thumbnail_url: 'https://example.com/thumbnail.jpg',
					author: `Author ${items.value.length + i + 1}`,
					name: `Photo ${items.value.length + i + 1}`,
					description: `This is the description of Photo ${items.value.length + i + 1}.`
				}))
				resolve(data)
			}, 1000)
		})
		items.value = [...items.value, ...newItems]
		loading.value = false
	}

	const handleScroll = () => {
		const container = scrollContainer.value
		if (container.scrollTop + container.clientHeight >= container.scrollHeight - 100) {
			fetchData()
		}
	}

	onMounted(() => {
		fetchData()
	})
</script>

<style scoped>
	.infinite-scroll-list {
		height: 100vh;
		overflow-y: auto;
	}

	.loading-indicator {
		display: flex;
		justify-content: center;
		padding: 20px;
	}
</style>